package com.chenyongjing.design.pattern.flyweight.pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;

/**
 * 模拟数据库连接池
 */
public class ConnectionPool {
    private Vector<Connection> pool;

    private String url = "jdbc:mysql://localhost:3306/test";
    private String username="root";
    private String password="root";
    private String driverName = "com.mysql.jdbc.Driver";
    private int poolSize =100;

    public ConnectionPool() {
        pool = new Vector<Connection>(poolSize);

        for (int i=0;i<poolSize;i++){
            try {
                Class.forName(driverName);
                Connection con = DriverManager.getConnection(url,username,password);
                pool.add(con);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 连接方法
     * @return
     */
    public synchronized Connection getConnection(){
        if (pool.size()>0){
            Connection con = pool.get(0);
            pool.remove(con);
            return con;
        }
        return null;
    }

    /**
     * 释放方法
     * @param connection
     */
    public synchronized void release(Connection connection){
        pool.add(connection);
    }
}
